import { h, ref } from 'vue';
import { NSwitch } from 'naive-ui';
import { cloneDeep } from 'lodash-es';
import { FormSchema } from '@/components/Form';
import { validate } from '@/utils/validateUtil';
import { renderImage } from '@/utils';
import { Switch } from '@/api/storeProduct';
import { useDictStore } from '@/store/modules/dict';
import { usePermission } from '@/hooks/web/usePermission';

const dict = useDictStore();
const { hasPermission } = usePermission();
const $message = window['$message'];

export class State {
  public id = 0; // 主键id
  public title = ''; // 商品标题
  public subtitle = ''; // 商品子标题
  public code = ''; // 商品编码
  public shareContent = ''; // 分享文案
  public image = ''; // 商品主图
  public images = [{
    image: ''
  }]; // 商品图片
  public imagesList = [];
  public price = 0; // 售价（分）
  public stock = 0; // 库存
  public limit = null; // 是否限购
  public fakeSale = 0; // 虚拟销量
  public sale = 0; // 真实销量
  public isHot = 2; // 是否热门
  public status = 2; // 上架状态
  public sort = 999; // 排序
  public createdAt = ''; // 创建时间
  public updatedAt = ''; // 更新时间
  public deletedAt = ''; // 删除时间
  public content = ''; //详情
  public attrs = [
    {
      name: '',
      vallue: ''
    }
  ]; //属性
  public skus = [
    {
      stock: '0',
      name: '',
      code: '',
      price: ''
    }
  ]; //规格


  constructor(state?: Partial<State>) {
    if (state) {
      Object.assign(this, state);
    }
  }
}

export function newState(state: State | Record<string, any> | null): State {
  if (state !== null) {
    if (state instanceof State) {
      return cloneDeep(state);
    }
    return new State(state);
  }
  return new State();
}

// 表单验证规则
export const rules = {
  title: {
    required: true,
    trigger: ['blur', 'input'],
    type: 'string',
    message: '请输入商品标题',
  },
  code: {
    required: true,
    trigger: ['blur', 'input'],
    type: 'string',
    message: '请输入商品编码',
  },
  image: {
    required: true,
    trigger: ['blur', 'input'],
    type: 'string',
    message: '请输入商品主图',
  },
  price: {
    required: true,
    trigger: ['blur', 'input'],
    type: 'number',
    validator: validate.amount,
  },
  stock: {
    required: true,
    trigger: ['blur', 'input'],
    type: 'number',
    message: '请输入库存',
  },
  limit: {
    required: true,
    trigger: ['blur', 'input'],
    type: 'number',
    message: '请输入是否限购',
  },
  fakeSale: {
    required: true,
    trigger: ['blur', 'input'],
    type: 'number',
    message: '请输入虚拟销量',
  },
  sale: {
    required: true,
    trigger: ['blur', 'input'],
    type: 'number',
    message: '请输入真实销量',
  },
  isHot: {
    required: true,
    trigger: ['blur', 'input'],
    type: 'number',
    message: '请输入是否热门',
  },
  status: {
    required: true,
    trigger: ['blur', 'input'],
    type: 'number',
    message: '请输入上架状态',
  },
  sort: {
    required: true,
    trigger: ['blur', 'input'],
    type: 'number',
    message: '请输入排序',
  },
};

// 表格搜索表单
export const schemas = ref<FormSchema[]>([
  {
    field: 'title',
    component: 'NInput',
    label: '商品标题',
    componentProps: {
      placeholder: '请输入商品标题',
      onUpdateValue: (e: any) => {
        console.log(e);
      },
    },
  },
  {
    field: 'isHot',
    component: 'NRadioGroup',
    label: '是否热门',
    giProps: {
      //span: 24,
    },
    componentProps: {
      options: dict.getOption('<nil>'),
      onUpdateChecked: (e: any) => {
        console.log(e);
      },
    },
  },
  {
    field: 'status',
    component: 'NRadioGroup',
    label: '上架状态',
    giProps: {
      //span: 24,
    },
    componentProps: {
      options: dict.getOption('<nil>'),
      onUpdateChecked: (e: any) => {
        console.log(e);
      },
    },
  },
]);

// 表格列
export const columns = [
  {
    title: '主键id',
    key: 'id',
    align: 'left',
    width: -1,
  },
  {
    title: '商品标题',
    key: 'title',
    align: 'left',
    width: -1,
  },
  {
    title: '商品编码',
    key: 'code',
    align: 'left',
    width: -1,
  },
  {
    title: '商品主图',
    key: 'image',
    align: 'left',
    width: -1,
    render(row: State) {
      return renderImage(row.image);
    },
  },
  {
    title: '售价（分）',
    key: 'price',
    align: 'left',
    width: -1,
  },
  {
    title: '库存',
    key: 'stock',
    align: 'left',
    width: -1,
  },
  {
    title: '真实销量',
    key: 'sale',
    align: 'left',
    width: -1,
  },
  {
    title: '是否热门',
    key: 'isHot',
    align: 'left',
    width: -1,
    render(row: State) {
      return h(NSwitch, {
        value: row.isHot === 1,
        checked: '开启',
        unchecked: '关闭',
        disabled: !hasPermission(['/storeProduct/switch']),
        onUpdateValue: function (e) {
          console.log('onUpdateValue e:' + JSON.stringify(e));
          row.isHot = e ? 1 : 2;
          Switch({ id: row.id, key: 'is_hot', value: row.isHot }).then((_res) => {
            $message.success('操作成功');
          });
        },
      });
    },
  },
  {
    title: '上架状态',
    key: 'status',
    align: 'left',
    width: -1,
    render(row: State) {
      return h(NSwitch, {
        value: row.status === 1,
        checked: '开启',
        unchecked: '关闭',
        disabled: !hasPermission(['/storeProduct/switch']),
        onUpdateValue: function (e) {
          console.log('onUpdateValue e:' + JSON.stringify(e));
          row.status = e ? 1 : 2;
          Switch({ id: row.id, key: 'status', value: row.status }).then((_res) => {
            $message.success('操作成功');
          });
        },
      });
    },
  },
  {
    title: '排序',
    key: 'sort',
    align: 'left',
    width: -1,
  },
];

// 加载字典数据选项
export function loadOptions() {
  dict.loadOptions(['sys_normal_disable']);
}